import type { BaseController } from '@/controller/BaseAppliance/definition'
import type { ApplianceBrand } from '@/types/appliance'
import type { Notice } from '@/types/notice'
import { toPage } from '@/utils/mpHelper'
import { reConnect } from '@/utils/waitforpairing'
// import { getPairingInfo } from '@/api/content'

export type NoticeLinkPayload = {
  type: string
  brand: ApplianceBrand
  vib: string
  control: BaseController.Control
  notice: Notice
}
export type NoticeLinkCallback = (payload: NoticeLinkPayload) => any
export type NoticeControlOptions = {
  externalMethods: Record<string, NoticeLinkCallback>
}

export function useNoticeControl(control: BaseController.Control, options?: NoticeControlOptions) {
  const linkCallbacks: Record<string, NoticeLinkCallback> = {
    reconnect: ({ vib }) => reConnect(vib, '通知家电离线重连'),
    getHelp: ({ vib }) =>
      toPage('/pages/pairing/help/help', {
        vib,
      }),
    ...options?.externalMethods,
  }

  /**
   * 联系客服
   */
  function contactService(phoneNumber: string) {
    uni.makePhoneCall({ phoneNumber })
  }

  /**
   * 特殊方法
   */
  function onLinkClick(notice: Notice, method: string) {
    const { type, brand, vib } = control.store._datasource
    const callbackMethod = linkCallbacks[method]
    if (typeof callbackMethod !== 'function') {
      return console.error(`Link method called "${method}" does not exist`)
    }

    callbackMethod({
      type,
      brand,
      vib,
      control,
      notice,
    })
  }
  function onLandingClick(landingPage: string) {
    return toPage(`/${landingPage}`)
  }

  // const clickReset = actionDebounce({
  //   call: async (vib: string) => {
  //     const res = await getPairingInfo(vib)
  //     const errors = res.data.step_list?.[0]?.errors
  //     return errors
  //   },
  //   then: (errors) => {
  //     const globalData = getApp().globalData
  //     if (!globalData || !errors) {
  //       return onResetFailed()
  //     }

  //     globalData.errors = errors
  //     toPage('/pages/pairing/help/help', {
  //       vib: props.control.store._datasource.vib,
  //     })
  //   },
  //   catch: () => onResetFailed(),
  // })
  // function onResetFailed() {
  //   uni.showModal({
  //     showCancel: false,
  //     content: '获取重置步骤失败',
  //   })
  // }

  return {
    contactService,
    onLinkClick,
    onLandingClick,
  }
}
